package com.wang.tx.core;

import java.util.ArrayList;
import java.util.List;

// 当执行失败或出异常的时候，可以进行重试的Tx
public class RetryTx extends Tx {
    private int retryCount = 1;
    private Tx tx;

    public RetryTx(int retryCount, Tx tx) {
        this.retryCount = Math.max(retryCount, 1);
        this.tx = tx;
    }

    @Override
    protected void prepare() throws Throwable {
        List<Throwable> list = new ArrayList<>(retryCount);
        for (int i = 0; i < retryCount; i++) {
            try {
                tx.prepare();
                break;
            } catch (Throwable thr) {
                list.add(thr);
            }
        }
        if (list.size() != 0) throw list.get(list.size() - 1);
    }

    @Override
    protected boolean execute() throws Throwable {
        List<Throwable> list = new ArrayList<>(retryCount);
        boolean isOk = false;
        for (int i = 0; i < retryCount; i++) {
            try {
                isOk = tx.execute();
                if (isOk) break;
            } catch (Throwable thr) {
                list.add(thr);
            }
        }
        if (isOk) {
            return true;
        } else {
            throw list.get(list.size() - 1);
        }
    }

    @Override
    protected void commit() {
        tx.commit();
    }

    @Override
    protected void rollback() {
        tx.rollback();
    }
}
